/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.cib.fintech.entrustedinvestment.biz.service.impl;

import com.cib.fintech.entrustedinvestment.biz.domain.MbUser;
import com.cib.fintech.entrustedinvestment.exception.EntityExistException;
import com.cib.fintech.entrustedinvestment.utils.ValidationUtil;
import com.cib.fintech.entrustedinvestment.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.cib.fintech.entrustedinvestment.biz.repository.MbUserRepository;
import com.cib.fintech.entrustedinvestment.biz.service.MbUserService;
import com.cib.fintech.entrustedinvestment.biz.service.dto.MbUserDto;
import com.cib.fintech.entrustedinvestment.biz.service.dto.MbUserQueryCriteria;
import com.cib.fintech.entrustedinvestment.biz.service.mapstruct.MbUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.cib.fintech.entrustedinvestment.utils.PageUtil;
import com.cib.fintech.entrustedinvestment.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zqk
* @date 2020-09-19
**/
@Service
@RequiredArgsConstructor
public class MbUserServiceImpl implements MbUserService {

    private final MbUserRepository mbUserRepository;
    private final MbUserMapper mbUserMapper;

    @Override
    public Map<String,Object> queryAll(MbUserQueryCriteria criteria, Pageable pageable){
        Page<MbUser> page = mbUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(mbUserMapper::toDto));
    }

    @Override
    public List<MbUserDto> queryAll(MbUserQueryCriteria criteria){
        return mbUserMapper.toDto(mbUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public MbUserDto findById(Long id) {
        MbUser mbUser = mbUserRepository.findById(id).orElseGet(MbUser::new);
        ValidationUtil.isNull(mbUser.getId(),"MbUser","id",id);
        return mbUserMapper.toDto(mbUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MbUserDto create(MbUser resources) {
        if(mbUserRepository.findByUsername(resources.getUsername()) != null){
            throw new EntityExistException(MbUser.class,"username",resources.getUsername());
        }
        if(mbUserRepository.findByPhone(resources.getPhone()) != null){
            throw new EntityExistException(MbUser.class,"phone",resources.getPhone());
        }
        if(mbUserRepository.findByEmail(resources.getEmail()) != null){
            throw new EntityExistException(MbUser.class,"email",resources.getEmail());
        }
        return mbUserMapper.toDto(mbUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MbUser resources) {
        MbUser mbUser = mbUserRepository.findById(resources.getId()).orElseGet(MbUser::new);
        ValidationUtil.isNull( mbUser.getId(),"MbUser","id",resources.getId());
        MbUser mbUser1 = null;
        mbUser1 = mbUserRepository.findByUsername(resources.getUsername());
        if(mbUser1 != null && !mbUser1.getId().equals(mbUser.getId())){
            throw new EntityExistException(MbUser.class,"username",resources.getUsername());
        }
        mbUser1 = mbUserRepository.findByPhone(resources.getPhone());
        if(mbUser1 != null && !mbUser1.getId().equals(mbUser.getId())){
            throw new EntityExistException(MbUser.class,"phone",resources.getPhone());
        }
        mbUser1 = mbUserRepository.findByEmail(resources.getEmail());
        if(mbUser1 != null && !mbUser1.getId().equals(mbUser.getId())){
            throw new EntityExistException(MbUser.class,"email",resources.getEmail());
        }
        mbUser.copy(resources);
        mbUserRepository.save(mbUser);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            mbUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<MbUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MbUserDto mbUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", mbUser.getUsername());
            map.put("密码，加密存储", mbUser.getPassword());
            map.put("注册手机号", mbUser.getPhone());
            map.put("注册邮箱", mbUser.getEmail());
            map.put(" created",  mbUser.getCreated());
            map.put(" updated",  mbUser.getUpdated());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}